Collections.sort() method 是在java.util.Collections class之下,是用於元素的排序(默認升序)。
功能與java.util.Arrays.sort() method是差不多。
可以用在所有List的implementations 包括LinkedList 和ArrayList。
Collections.sort() method 有兩個overloaded methods,分別是:
Collections.sort(Collection)
默認升序的方式
Collections.sort(Collection, Comparator)
排序會表按Comparator的方式
例子1:
升序排列
import java.util.*;
public class Collectionsorting
{
public static void main(String[] args)
{
// 創建一個ArrayList
ArrayList<String> list1 = new ArrayList<String>();
list1.add("I");
list1.add("am");
list1.add("Martin");
//升序排列
Collections.sort(list1);
//顯示結果
System.out.println("List after the use of" + " Collection.sort() :\n" +list1);
}
}
例子2:
降序排列
import java.util.*;
public class Collectionsorting
{
public static void main(String[] args)
{
// 創建一個ArrayList
ArrayList<String> list1 = new ArrayList<String>();
list1.add("I");
list1.add("am");
list1.add("Martin");
//降序排列
Collections.sort(list1,Collections.reverseOrder());
//顯示結果
System.out.println("List after the use of" + " Collection.sort() :\n" +list1);
}
}
例子3:
排序會表按Comparator的方式
import java.util.*;
import java.lang.*;
import java.io.*;
// 一個Book的類
class Book
{
Int bookID;
String name, type;
// Constructor
public Book (int bookID, String name,
String type)
{
this. bookID = bookID;
this.name = name;
this. type = type;
}
// Book的資料
public String toString()
{
return this. bookID + " " + this.name +
" " + this. type;
}
}
class BookSort implements Comparator<Book>
{
//以book的ID升序排列
public int compare(Book a, Book b)
{
return a.bookID - b.bookID;
}
}
class Main
{
public static void main (String[] args)
{
ArrayList< Book > list3 = new ArrayList<Book>();
list3.add(new Book (1234, "Gogogo", "computer"));
list3.add(new Book (1698, "Happy", "art"));
list3.add(new Book (5468, "Martin", "music"));
System.out.println("Unsorted");
for (int i=0; i< list3.size(); i++)
System.out.println(list3.get(i));
Collections.sort(list3, new BookSort());
System.out.println("\nBook Sort");
for (int i=0; i< list3.size(); i++)
System.out.println(list3.get(i));
}
}